package com.drug.controller;
import com.drug.domain.DrugAtegory;
import com.drug.domain.DrugInformation;
import com.drug.domain.Result;
import com.drug.mapper.DrugQualityLevelMapper;
import com.drug.mapper.ManufacturerMapper;
import com.drug.service.*;
import com.drug.util.ExcelUtil;
import com.drug.util.ExcelUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 药品信息表控制层
 */
@Controller
@ResponseBody
public class DrugInformationController<privte> {

    @Autowired
    private DrugInformationSerice drugInformationSerice;

    @Autowired
    private Supplier2Service supplier2Service;

    @Autowired
    private SupplierService supplierService;
    @Autowired
    private DrugAtegoryService drugAtegoryService;

    @Autowired
    private DrugCategoryService drugCategoryService;

    @Autowired
    private ManufacturerMapper manufacturerMapper;

    @Autowired
    private DrugQualityLevelMapper drugQualityLevelMapper;

    /**
     * 新增药品信息
     */
    @ResponseBody
    @RequestMapping(value = "/DrugInformationController/insertDrugInformation", produces = "application/json; charset=utf-8")
    public Result insertDrugInformation(DrugInformation drugInformation,DrugAtegory DrugAtegory){
        int daId = drugAtegoryService.insertDrugAtegoryName(DrugAtegory);
        //map.put("daId",daId);
        drugInformation.setDiDaId(daId);
        Result result = drugInformationSerice.insertDrugInformation2(drugInformation);
        return result;
    }


    /**
     * 查询全部药品品目
     */
    @ResponseBody
    @RequestMapping(value = "/DrugInformationController/fandAll", produces = "application/json; charset=utf-8")
    public Result fandAll() {
        return drugInformationSerice.fandAll();
    }

    /**
     * 根据id进行删除
     */
    @RequestMapping(value = "/DrugInformationController/removeById", produces = "application/json; charset=utf-8")
    public String removeBydiId(Integer diId) {
        drugInformationSerice.removeBydiId(diId);
        return "redirect:/static/pages/01/drug01.html";
    }
    /**
     * 根据id进行删除
     */
    @RequestMapping(value = "/DrugInformationController/removeById1", produces = "application/json; charset=utf-8")
    public String removeBydiId1(Integer diId) {
        drugInformationSerice.removeBydiId(diId);
        return "redirect:/static/pages/01/drug01.html";
    }

    /**
     * 药品品目导出
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/DrugInformationController/getExcel")
    public String export(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String message = "";
        //获取数据
        List<DrugInformation> list = supplier2Service.findAll();
        //excel标题
        String[] title = {"药品目录号", "通用名", "剂型", "规格", "单位", "转换系数", "药品类别", "状态"};
        //excel文件名
        String fileName = "drugDa" + System.currentTimeMillis() + ".xls";
        //sheet名
        String sheetName = "样品信息表";
        String[][] content = new String[list.size()][];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            DrugInformation drugInformation = list.get(i);
            DrugAtegory drugAtegory = drugInformation.getDrugAtegory();
            Integer daNumber = null;
            if (drugAtegory != null) {
                daNumber = drugAtegory.getDaNumber();
            }
            content[i][0] = daNumber + "";
            //通用名
            String diName = drugInformation.getDiName();
            content[i][1] = diName + "";
            //剂型
            String diForm = drugInformation.getDiForm();
            content[i][2] = diForm + "";
            //规格
            String diSpecifications = drugInformation.getDiSpecifications();
            content[i][3] = diSpecifications + "";
            //单位
            content[i][4] = drugInformation.getDiUnit() + "";
            //转换系数
            content[i][5] = drugInformation.getDiCc() + "";
            //类别
            Integer diDaCategory = drugInformation.getDiDaCategory();
            String nameById = null;
            if (diDaCategory != null) {
                nameById = drugInformationSerice.findNameById(diDaCategory);
            }
            content[i][6] = nameById + "";
            //状态
            String diState = "";
            diState = drugInformation.getDiState();
            if (diState.equals("0")) {
                diState = "正常";
            } else {
                diState = "异常";
            }
            content[i][7] = diState + "";
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
            message = "SUCCESS";
        } catch (Exception e) {
            e.printStackTrace();
            message = "ERROR";
        }
        return null;
    }

    @RequestMapping(value="/DrugInformationController/inputExcel1", method = RequestMethod.POST)
    public String uploadTest(@RequestParam MultipartFile file, HttpServletRequest request){

        try {
            if(file==null) {
                return "上传文件不能为空";
            }
            String fileName = file.getOriginalFilename();
            if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
                return "上传文件格式错误，请上传后缀为.xls或.xlsx的文件";
            }

            boolean isExcel2003 = true;
            if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
                isExcel2003 = false;
            }
            InputStream is = file.getInputStream();
            Workbook wb = null;
            if (isExcel2003) {
                wb = new HSSFWorkbook(is);
            } else {
                wb = new XSSFWorkbook(is);
            }
            Sheet sheet = wb.getSheetAt(0);
            if(sheet!=null){
                //notNull = true;
            }
            for (int r = 1; r <= sheet.getLastRowNum(); r++) {
                Row row = sheet.getRow(r);
                if (row == null) {
                    continue;
                }
            }
        } catch (IOException e) {
        }
        return "asdsa";
    }


    /**
     * 导入excel
     *
     * @param request
     * @return
     * @throws ParseException
     */
    @RequestMapping("/inputExcel")
    public Result poiInfo(@RequestParam("file") MultipartFile file,HttpServletRequest request, ModelMap map) throws Exception {
        Result result = new Result();
        String message = "error";
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        //获取你导入文件的
        List<List<Object>> list = null;
        String fileName=file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        try {
            list = ExcelUtil.getExcelList(inputStream, file.getOriginalFilename());
            message = "success";
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (int i = 0; i < list.size(); i++) {
            List<Object> li = list.get(i);
            //先将品目号添加
            Map map1 = new HashMap();
            String daNumber = li.get(0).toString();
            map1.put("daNumber", daNumber);
            int daId = drugAtegoryService.addDrugAtegory(map1);
            //导入药品品目表
            String name = (String) li.get(1);//通用名
            String diForm = li.get(2).toString();//剂型
            String diSpecifications = li.get(3).toString();//规格
            String diUnit = li.get(4).toString();//单位
            String diCc = li.get(5).toString();//转换系数
            String diDaCategory = (String) li.get(6);//药品类别
            result = drugCategoryService.selectIdbyName(diDaCategory);
            int code = result.getCode();
            String cd = Integer.toString(code);
            String diState = li.get(7).toString();//状态
            if(diState.equals("正常")){
                diState="0";
            }else{
                diState="1";
            }
            //在添加药品信息
            HashMap hashMap = new HashMap();
            hashMap.put("diName", name);
            hashMap.put("diForm", diForm);
            hashMap.put("diSpecifications", diSpecifications);
            hashMap.put("diUnit", diUnit);
            hashMap.put("diCc", diCc);
            hashMap.put("diDaCategory", cd);
            hashMap.put("diState", diState);
            hashMap.put("daId", daId);
            //调用添加方法
             result = drugInformationSerice.addDrugInformation(hashMap);
        }
        map.addAttribute("message", message);
        result.setMsg("导入成功");

        return result ;
    }

    /**
     * 导入药品信息excel
     * @param file
     * @param request
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/inputExcel2")
    public String poiInfo(@RequestParam("file") MultipartFile file,HttpServletRequest request,HttpServletResponse response) throws Exception {
        List<List<Object>> list = ExcelUtil.getExcelList(file.getInputStream(), file.getOriginalFilename());
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        for (int i = 0; i < list.size(); i++) {
            List<Object> li = list.get(i);
            String diNumer = (String) li.get(0);
            String diName = (String) li.get(1);
            String diForm = (String) li.get(2);
            String diSpecifications = (String) li.get(3);
            String diUnit = (String) li.get(4);
            String diCc = (String) li.get(5);
            String mfName = (String) li.get(6);
            Integer mfId = manufacturerMapper.selectIdByName(mfName);
            String daName = (String) li.get(7);
            BigDecimal diBiddingPrice = new BigDecimal((String)li.get(8));
            String diApprovalNumber = (String) li.get(9);
            String diApprovalTerm = (String) li.get(10);
            String diImportDrugs = (String) li.get(11);
            if(diImportDrugs == "是"){
                diImportDrugs = "0";
            }else{
                diImportDrugs = "1";
            }
            String diMaterialQuality = (String) li.get(12);
            String diBunit = (String) li.get(13);
            BigDecimal diNewPrice = new BigDecimal((String)li.get(14));
            String diRetailPrice = ((String)li.get(15)) ;
            String dqln = (String) li.get(16);
            int d = drugQualityLevelMapper.selectIdByName(dqln);
            String diDqlName = Integer.toString(d);
            String diDqlexplain = (String) li.get(17);
            String diInspectionReport = (String) li.get(18);
            String diInspectionNumber = (String) li.get(19);
            String diInspectionTerm = (String) li.get(20);
            String diDescription = (String) li.get(21);
            String diTradingStatus = (String) li.get(22);
            if(diTradingStatus.equals("正常")){
                diTradingStatus="0";
            }else{
                diTradingStatus="1";
            }
            DrugAtegory drugAtegory = new DrugAtegory();
            drugAtegory.setDaName(daName);
            int daId = drugAtegoryService.insertDrugAtegoryName(drugAtegory);
            DrugInformation drugInformation = new DrugInformation();
            drugInformation.setDiDaId(daId);
            drugInformation.setDiNumer(diNumer);
            drugInformation.setDiName(diName);
            drugInformation.setDiForm(diForm);
            drugInformation.setDiSpecifications(diSpecifications);
            drugInformation.setDiUnit(diUnit);
            drugInformation.setDiCc(diCc);
            drugInformation.setDiDqlName(diDqlName);
            drugInformation.setDiTradingStatus(diTradingStatus);
            drugInformation.setDiRetailPrice(diRetailPrice);
            drugInformation.setDiNewPrice(diNewPrice);
            drugInformation.setDiBiddingPrice(diBiddingPrice);
            drugInformation.setDiApprovalNumber(diApprovalNumber);
            drugInformation.setDiApprovalTerm(diApprovalTerm);
            int i2 = Integer.parseInt(diImportDrugs);
            drugInformation.setDiImportDrugs(i2);
            drugInformation.setDiInspectionReport(diInspectionReport);
            int i3 = Integer.parseInt(diInspectionNumber);
            drugInformation.setDiInspectionNumber(i3);
            drugInformation.setDiInspectionTerm(diInspectionTerm);
            drugInformation.setDiDescription(diDescription);
            drugInformation.setDiMaterialQuality(diMaterialQuality);
            drugInformation.setDiDqlexplain(diDqlexplain);
            drugInformation.setDiMfId(mfId);

            //调用添加方法
            drugInformationSerice.insertDrugInformation2(drugInformation);
            response.getWriter().write( "<script>alert('导入成功')</script>");
        }
        return null;
    }


    private void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "utf-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 下载模板
     */
    @RequestMapping("/DrugInformationController/download")
    @ResponseBody
    public void downloadSampleInfo(HttpServletResponse response, HttpServletRequest request) throws IOException {
        OutputStream os = null;// 输出流
        File path = new File(ResourceUtils.getURL("classpath:static/download/bb.xls").getPath());
        InputStream fis = new FileInputStream(path);
        // 手动创建一个elsx文件
        /*        XSSFWorkbook wb = new XSSFWorkbook(fis);*/
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook(fis);
        String fileName = "药品目录.xls";
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
        os = response.getOutputStream();
        hssfWorkbook.write(os);
        os.flush();
        os.close();
    }


    /**
     * 下载药品信息模板
     */
    @RequestMapping("/DrugInformationController/download2")
    @ResponseBody
    public void downloadDrugInformation(HttpServletResponse response, HttpServletRequest request) throws IOException {
        OutputStream os = null;// 输出流
        File path = new File(ResourceUtils.getURL("classpath:static/download/cc.xls").getPath());
        InputStream fis = new FileInputStream(path);
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook(fis);
        String fileName = "药品信息.xls";
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
        os = response.getOutputStream();
        hssfWorkbook.write(os);
        os.flush();
        os.close();
    }


    /**
     * 根据id回显
     */
    @RequestMapping("/selectSampleById")
    @ResponseBody
    public Result selectDiById(@RequestParam(value = "diId", required = false)Integer diId){
        return drugInformationSerice.selectDiById(diId);

    }

    /**
     * 根据id回显药品信息
     */
    @RequestMapping("/selectDrugInformationById")
    @ResponseBody
    public Result selectDrugInformationById(@RequestParam(value = "diId", required = false)Integer diId){
        return drugInformationSerice.selectDrugInformationById(diId);
    }

    /**
     * 修改药品品目
     */
    @RequestMapping("/DrugInformationController/updateDrugInformation")
    @ResponseBody
    public Result updateDrugInformation(@RequestParam Map<String ,Object> map){
        Result result = drugInformationSerice.updateDrugInformation(map);
        return result;
    }

    /**
     * 修改药品信息
     */
    @RequestMapping(value="/DrugInformationController/updateDrugInformation2", produces = "application/json; charset=utf-8")
    @ResponseBody
    public Result updateDrugInformation(DrugInformation drugInformation,DrugAtegory drugAtegory){
        int daId = drugAtegoryService.updateDrugAtegorydaName(drugAtegory);
        drugInformation.setDiDaId(daId);
        Result result = drugInformationSerice.updateDrugInformation2(drugInformation);

        return result;
    }


    /**
     *
     * 根据条件分页查询所有或多条件查询
     * @param map
     * @param pageNum
     * @return
     */
    @RequestMapping(value = "/findConditional")
    private Result findConditional(@RequestParam Map<String,Object> map,@RequestParam(required=true,defaultValue="1")Integer pageNum){
        return  supplier2Service.findConditional(map,pageNum);
    }





    /**
     * 药品信息导出
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/DrugInformationController/getExcel1")
    public String exportDi(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String message = "";
        //获取数据
        List<DrugInformation> list = supplier2Service.findAll();
        //excel标题
        String[] title = {"药品流水号","通用名","剂型","规格","单位","转换系数","生产企业","商品名称","中标价","质量层次","药品类别","交易状态"};
        //excel文件名
        String fileName = "drugDi"+System.currentTimeMillis()+".xls";
        //sheet名
        String sheetName = "样品信息表";
        String [][] content = new String[list.size()][];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            DrugInformation drugInformation = list.get(i);
            //药品流水号
            String diNumer = drugInformation.getDiNumer();
            content[i][0] = diNumer+"";
            //通用名
            String diName = drugInformation.getDiName();
            content[i][1] = diName+"";
            //剂型
            String diForm = drugInformation.getDiForm();
            content[i][2] = diForm+"";
            //规格
            String diSpecifications = drugInformation.getDiSpecifications();
            content[i][3] = diSpecifications+"";
            //单位
            content[i][4] = drugInformation.getDiUnit()+"";
            //转换系数
            content[i][5] = drugInformation.getDiCc()+"";
            //生产企业
            String mfNameById = null;
            String daName= null;
            DrugAtegory drugAtegory = drugInformation.getDrugAtegory();
            if (drugAtegory!=null){
                String daMName = drugAtegory.getDaMName();
                if (daMName!=null){
                    mfNameById  = supplier2Service.findMfNameById(Integer.parseInt(daMName));
                }
                daName = drugAtegory.getDaName();
            }
            content[i][6] =mfNameById+"";
            //商品名称
            content[i][7] = daName +"";
            //中标价
            content[i][8] = drugInformation.getDiNewPrice() +"";
            //质量层次
            String dqlNameById= null;
            String diDqlName = drugInformation.getDiDqlName();
            if (diDqlName!=null){
                dqlNameById = supplier2Service.findDqlNameById(Integer.parseInt(diDqlName));
            }
            content[i][9] =dqlNameById+"";
            //类别
            Integer diDaCategory = drugInformation.getDiDaCategory();
            String nameById =null;
            if (diDaCategory!=null){
                nameById  = supplier2Service.findNameById(diDaCategory);
            }
            content[i][10] = nameById +"";
            //交易状态
            String diTradingStatu="";
            String diTradingStatus = drugInformation.getDiTradingStatus();
            if (diTradingStatus!=null){
                if (diTradingStatus.equals("0")){
                    diTradingStatu="正常";
                }else {
                    diTradingStatu="异常";
                }
            }
            content[i][11] = diTradingStatu +"";
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
            message = "SUCCESS";
        } catch (Exception e) {
            e.printStackTrace();
            message = "ERROR";
        }
        return null;
    }

    /**
     *
     * 查询药品交易明细
     * @param map
     * @param pageNum
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/DrugInformationController/selectTransactionDetail")
    private Result selectTransactionDetail(@RequestParam Map<String,Object> map,@RequestParam(required=true,defaultValue="1")Integer pageNum){
        return  drugInformationSerice.selectTransactionDetail(map,pageNum);
    }

    /**
     * 查询通用名是否已存在
     * @param diName
     * @return
     */
    @ResponseBody
    @RequestMapping("/DrugInformationController/finddiName")
    public Result diName(String diName){
        return drugInformationSerice.diName(diName);
    }


    /**
     * 查询流水号是否已存在
     * @param diNumer
     * @return
     */
    @ResponseBody
    @RequestMapping("/DrugInformationController/findLSNumer")
    public Result diNumer(String diNumer){
        return drugInformationSerice.diNumer(diNumer);
    }

}
